<template>
  <view class="l-warp">
    <view class="swiper_container">
      <swiper
        @change="change"
        style="height: 380rpx"
        :interval="5000"
        v-if="imgList.length !== 0"
      >
        <swiper-item v-for="(item, i) in imgList" :key="i">
          <image
            class="u-swiper-image"
            @click="viewImg(i)"
            @load="imgLoad(item, i)"
            @error="loadErr(item, i)"
            :src="item"
            mode="round"
          ></image>
        </swiper-item>
      </swiper>
      <view class="indicator-dots">
        <view
          class="indicator-dots-item"
          v-for="(item, index) in imgList"
          :key="index"
          :class="[current == index ? 'indicator-dots-active' : '']"
        ></view>
      </view>
    </view>
  </view>
</template>
<script>
export default {
  data() {
    return {
      current: 0,
      canvasWidth: 0,
      canvasheight: 0,
    };
  },
  onLoad() {
    this.getDetail(option.id);
  },
  methods: {
    getDetail(id) {
			this.$u.get('xxx', { id: id, type: '1' }).then(res => {
				// 先占位 可以处理成对象 兼容后续添加
				this.imgList = res.data.pic.map((item, i) => {
					let url = this.baseUrl + item.fileUrl;
					return (url = `data:${url}`);
				});
				this.dataInfo = res.data;
				// 开启顺序加载
				this.openImgLoad();
			});
		},
    openImgLoad() {
      if (!this.imgList.length) return
      const imgItem = this.dataInfo?.pic[0] || {};
      this.canvasPart({
        ...imgItem,
        index: "0",
        url: this.imgList[0].replace("data:", ""),
      });
    },
    loadErr(item, index) {
      // 如果有证明第一次加载
      if (item.includes("data:")) return;
      this.imgLoad(item, index);
    },
    imgLoad(item, index) {
      // 当前图片加载完毕，开始加载下一张
      const imgList = this.imgList;
      // index 从0开始
      const nextIndex = ++index;
      if (nextIndex === imgList.length) return;
      const imgItem = this.dataInfo.pic[nextIndex];
      this.canvasPart({
        ...imgItem,
        index: nextIndex,
        url: imgList[nextIndex].replace("data:", ""),
      });
    },
    canvasPart(options) {
      // index,要改变的数组索引
      const { url, personDataList = null, index = 0 } = options;
      console.log(`写入第${index}个图片---`);
      const setImgList = (file) => that.$set(that.imgList, index, file);
      const ctx = uni.createCanvasContext("handWriting", this); //创建绘图对象;
      const that = this;
      // 必须要 personDataList 存在并且是一个数组 并且要有值 才可以进行动态渲染
      if (
        !(personDataList && Array.isArray(personDataList)) &&
        personDataList.length
      ) {
        setImgList(url);
        return;
      }
      uni.getImageInfo({
        src: url,
        type: "png",
        success: (imgInfo) => {
          console.log(imgInfo, "info");
          that.canvasWidth = imgInfo.width + "px";
          that.canvasheight = imgInfo.height + "px";
          // 设置图片在canvas上 前面两个0,0是边距, 后面是宽高
          ctx.drawImage(imgInfo.path, 0, 0, imgInfo.width, imgInfo.height);
          // 动态画矩形
          personDataList.forEach((item) => {
            // 设置字体
            ctx.font = "26px bold 黑体";
            // 设置颜色
            ctx.fillStyle = "#67C23A";
            ctx.fillText("person " + item.confidence, item.x, item.y - 8);
            ctx.lineWidth = 4;
            ctx.strokeStyle = "#67C23A";
            ctx.strokeRect(item.x, item.y, item.width, item.height);
          });
          ctx.draw(true, () => {
            console.log("over draw ------");
            uni.canvasToTempFilePath({
              canvasId: "handWriting",
              destWidth: imgInfo.width,
              destHeight: imgInfo.height,
              success: (res) => {
                console.log("over draw render ing ------", res);
                setImgList(res.tempFilePath);
                // 清空画板
                ctx.clearRect(0, 0, that.canvasWidth, that.canvasheight);
                ctx.draw();
              },
              fail: (err) => {
                // 如果我们导出失败，那么我们进行重新绘制
                console.log(err, "canvasToTempFilePath 导出图片失败 重启");
                this.canvasPart(options);
              },
            });
          });
        },
        fail: (err) => {
          // 走到这里说明路径错误 跳过
          console.log("load fail", err);
          that.loadErr(url, index);
        },
      });
    },
    viewImg(i) {
      uni.previewImage({
        current: i,
        urls: this.imgList,
      });
    },
    change(e) {
      this.current = e.detail.current;
    },
  },
};
</script>

<style lang="scss">
.u-swiper-image {
  width: 100%;
  will-change: transform;
  height: 100%;
  /* #ifndef APP-NVUE */
  display: block;
  /* #endif */
  /* #ifdef H5 */
  pointer-events: none;
  /* #endif */
}

.swiper_container {
  position: relative;
  .indicator-dots {
    width: 100%;
    position: absolute;
    bottom: 10rpx;
    padding: 10rpx 0;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .indicator-dots-item {
    width: 14rpx;
    height: 14rpx;
    margin: 0 6rpx;
    border-radius: 20rpx;
    transition: all 0.5s;
    background-color: rgba(0, 0, 0, 0.3);
  }

  .indicator-dots-active {
    width: 34rpx;
    background-color: rgba(255, 255, 255, 0.8);
  }
}
</style>
